﻿using System.Collections;
using log4net;
using MPMovieCatalog.Exception;
using MPMovieCatalog.Util;

namespace MPMovieCatalog.Export
{
    public abstract class Exporter : IWorkable
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Exporter));

        private ProgressWorker m_progressWorker;

        public Exporter(string title, ArrayList movies, string fileName)
        {
            Title = title;
            Movies = movies;
            FileName = fileName;
        }

        public string Title { get; set; }

        public ArrayList Movies { get; set; }

        public string FileName { get; set; }

        public bool IsCancelled { get; set; }

        public string DoWork(ProgressWorker worker)
        {
            try
            {
                m_progressWorker = worker;
                Export();
                return string.Format(ResourceUtils.GetString("export", 6), Movies.Count, FileName);
            }
            catch (System.Exception e)
            {
                log.Error(string.Format("Error exporting movies, message: {0}", e.Message), e);
                throw new MPMovieCatalogException(ResourceUtils.GetString("export", 7), e);
            }
        }

        protected void OnProgress(int itemNumber)
        {
            int percent = itemNumber / Movies.Count * 100;
            OnProgress(percent, string.Format(ResourceUtils.GetString("export", 5), itemNumber.ToString(), Movies.Count));
        }

        protected void OnProgress(int percent, string label)
        {
            m_progressWorker.OnProgress(percent, label);
        }

        protected bool CancellationPending
        {
            get
            {
                return m_progressWorker.CancellationPending;
            }
        }


        protected abstract void Export();
    }
}
